<?php

namespace App\Http\Controllers\Admin;

use App\Events\permChangeEvent;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\MenuCreateRequest;
use App\Http\Requests\Admin\MenuUpdateRequest;
use App\Models\Admin\Menu;
use Event;
use Illuminate\Http\Request;

class MenuController extends Controller
{
    protected $fields = [
        'name'        => '',
        'alias'       => '',
        'description' => '',
        'f_pid'       => '',
        'icon'        => '',
        'listorder'   => '',
		'display'     => '1',
    ];

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $f_pid = 0)
    {
        $f_pid = (int) $f_pid;
        if ($request->ajax()) {
            $data                 = array();
            $data['draw']         = $request->get('draw');
            $start                = $request->get('start');
            $length               = $request->get('length');
            $order                = $request->get('order');
            $columns              = $request->get('columns');
            $search               = $request->get('search');
            $f_pid                = $request->get('f_pid', 0);
            $data['recordsTotal'] = Menu::where('f_pid', $f_pid)->count();
            if (strlen($search['value']) > 0) {
                $data['recordsFiltered'] = Menu::where('f_pid', $f_pid)->where(function ($query) use ($search) {
                    $query
                        ->where('name', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('description', 'like', '%' . $search['value'] . '%')
                        ->orWhere('alias', 'like', '%' . $search['value'] . '%');
                })->count();
                $data['data'] = Menu::where('f_pid', $f_pid)->where(function ($query) use ($search) {
                    $query->where('name', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('description', 'like', '%' . $search['value'] . '%')
                        ->orWhere('alias', 'like', '%' . $search['value'] . '%');
                })
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            } else {
                $data['recordsFiltered'] = Menu::where('f_pid', $f_pid)->count();
                $data['data']            = Menu::where('f_pid', $f_pid)->
                    skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            }

            return response()->json($data);
        }
        $datas['f_pid'] = $f_pid;
        if ($f_pid > 0) {
            $datas['data'] = Menu::find($f_pid);
        }

        return view('admin.menu.index', $datas);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($f_pid)
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
        $data['f_pid'] = $f_pid;

        return view('admin.menu.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param PremissionCreateRequest|Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(MenuCreateRequest $request)
    {
        $menu = new Menu();
        foreach (array_keys($this->fields) as $field) {
            $menu->$field = $request->get($field, $this->fields[$field]);
        }
        $menu->save();
        Event::fire(new permChangeEvent());

        //触发事件
        event(new \App\Events\userActionEvent('\App\Models\Admin\Menu', $menu->id, 1, '添加了菜单:' . $menu->name . '(' . $menu->alias . ')'));

        return redirect('/admin/menu/' . $menu->f_pid)->withSuccess('添加成功！');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $menu = Menu::find((int) $id);
        if (!$menu) {
            return redirect('/admin/menu')->withErrors("找不到该权限!");
        }

        $data = ['id' => (int) $id];
        foreach (array_keys($this->fields) as $field) {
            $data[$field] = old($field, $menu->$field);
        }

        return view('admin.menu.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param MenuUpdateRequest|Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(MenuUpdateRequest $request, $id)
    {
        $menu = Menu::find((int) $id);
        foreach (array_keys($this->fields) as $field) {
            $menu->$field = $request->get($field, $this->fields[$field]);
        }
        $menu->save();

        //触发事件
        Event::fire(new permChangeEvent());
        event(new \App\Events\userActionEvent('\App\Models\Admin\Menu', $menu->id, 3, '修改了菜单:' . $menu->name . '(' . $menu->alias . ')'));

        return redirect('admin/menu/' . $menu->f_pid)->withSuccess('修改成功！');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $child = Menu::where('f_pid', $id)->first();

        if ($child) {
            return redirect()->back()
                ->withErrors("请先将该菜单的子菜单删除后再做删除操作!");
        }
        $tag = Menu::find((int) $id);
        if ($tag) {
            $tag->delete();
        } else {
            return redirect()->back()
                ->withErrors("删除失败");
        }

        //触发事件
        Event::fire(new permChangeEvent());
        //写一条记录
        event(new \App\Events\userActionEvent('\App\Models\Admin\Menu', $tag->id, 2, '删除了权限:' . $tag->name . '(' . $tag->alias . ')'));

        return redirect()->back()
            ->withSuccess("删除成功");
    }
}
